package com.goldmantis.ssm.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goldmantis.ssm.bean.SysUser;
import com.goldmantis.ssm.service.SysUserService;
import com.goldmantis.ssm.util.ReturnMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class SysUserController {


    @Autowired
    private SysUserService sysUserService;

    @RequestMapping("/user")
    @ResponseBody
    public ReturnMessage get(@RequestParam(value ="pageIndex",defaultValue = "1") Integer pageIndex, @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize){

        //引入pagehelper 插件
        PageHelper.startPage(pageIndex,10);
        //startPage 后紧跟这个查询方法
        List<SysUser> sysUsers = sysUserService.get();

        PageInfo pageInfo=new PageInfo(sysUsers,pageSize);

        return ReturnMessage.success().add("pageInfo",pageInfo);
    }

    @RequestMapping(value = "/user",method = RequestMethod.POST)
    @ResponseBody
    public ReturnMessage add(@Valid SysUser sysUser, BindingResult bindingResult) {
        //引入JSR303校验 支持tomcat 7 以上服务器
        if(bindingResult.hasErrors()){
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();

            Map<String,Object> map=new HashMap<String,Object>();
            for (FieldError fieldError :fieldErrors){
                map.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
            return ReturnMessage.failure().add("errorFields",map);
        }
        sysUserService.insert(sysUser);

        return ReturnMessage.success();
    }

    /*
    userId必须要与实体类的Id列匹配，否则无法接受主键列，导致更新失败
     */
    @RequestMapping(value = "/user/{userId}",method = RequestMethod.PUT)
    @ResponseBody
    public ReturnMessage edit(SysUser sysUser){
        sysUserService.update(sysUser);
        return ReturnMessage.success();
    }

    @ResponseBody
    @RequestMapping(value = "/user/{id}",method = RequestMethod.DELETE)
    public ReturnMessage delete(@PathVariable("id") Integer id){
        sysUserService.delete(id);
        return ReturnMessage.success();
    }


    @ResponseBody
    @RequestMapping(value = "/user/checkUser")
    public ReturnMessage checkUser(){
        boolean result= sysUserService.CheckUser();
        return ReturnMessage.success().add("userExist",result);
    }
}
